package com.vhuomai.product.home.service.impl;

import com.vhuomai.mybatis.mapper.page.Page;
import com.vhuomai.mybatis.mapper.page.PageRequest;
import com.vhuomai.product.entity.BaseProduct;
import com.vhuomai.product.home.dto.HomeProductChoose;
import com.vhuomai.product.home.dto.HomeProductInfo;
import com.vhuomai.product.home.dto.HomeProductReq;
import com.vhuomai.product.home.entity.BaseHomeProduct;
import com.vhuomai.product.home.mapper.HomeProductMapper;
import com.vhuomai.product.home.service.HomeProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class HomeProductServiceImpl implements HomeProductService {
    @Autowired
    private HomeProductMapper homeProductMapper;

    @Override
    public void createHomeProduct(HomeProductReq request) {
        List<BaseHomeProduct> homeProducts = new ArrayList<>();
        request.getProductIds().forEach(productId -> {
            BaseHomeProduct homeProduct = new BaseHomeProduct();
            homeProduct.setId(null);
            homeProduct.setCategoryId(request.getHomeCategoryId());
            homeProduct.setProductId(productId);
            homeProduct.setCreateTime(LocalDateTime.now());
            homeProduct.setUpdateTime(LocalDateTime.now());
            homeProducts.add(homeProduct);
        });
        homeProductMapper.insertAll(homeProducts);
    }

    @Override
    public void deleteHomeProduct(List<Integer> ids) {
        homeProductMapper.deleteAll(ids);
    }

    @Override
    public List<HomeProductInfo> homeProductDetail(Integer homeCategoryId) {
        return homeProductMapper.findByCategory(homeCategoryId);
    }

    @Override
    public Page<BaseProduct> homeProductChoose(HomeProductChoose request) {
        Collection<Integer> productIds = new ArrayList<>();
        homeProductMapper.findByCategory(request.getHomeCategoryId())
            .forEach(homeProductInfo -> {
                productIds.add(homeProductInfo.getId());
            });
        PageRequest pageRequest = request.getPageRequest();
        pageRequest.setAsc(false);
        pageRequest.setOrderBy("create_time");
        return homeProductMapper.findProductList(productIds, pageRequest);
    }
}
